package cn.harry.cabinet.view.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.harry.cabinet.databinding.FragmentUserManagementBinding
import cn.harry.cabinet.model.entity.User
import cn.harry.cabinet.utils.logConfigChange
import cn.harry.cabinet.view.adapter.UserAdapter
import cn.harry.cabinet.view.dialog.DeleteConfirmationDialogFragment
import cn.harry.cabinet.view.dialog.UserFormDialogFragment
import cn.harry.cabinet.viewmodel.UserViewModel

class UserManagementFragment : BaseFragment() {
    
    private var _binding: FragmentUserManagementBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException("Fragment binding is null. Fragment may have been destroyed.")
    private lateinit var userAdapter: UserAdapter
    
    // 使用ViewModel获取真实数据
    private val userViewModel: UserViewModel by viewModels()
    
    // 添加防抖标志，避免频繁触发加载
    private var isLoadingMore = false
    
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentUserManagementBinding.inflate(inflater, container, false)
        return binding.root
    }
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        setupRecyclerView()
        setupSearchFunction()
        setupObservers()
        setupRefreshLayout()
        setupAddUserButton()
        setupResetButton()
        setupToggleSearch()
        setupLoadMoreListener()
        setupEmptyState()
        
        // 清除搜索框焦点，避免弹出键盘
        clearSearchFocus()
        
        // 初始加载数据
        userViewModel.refreshUsers()
    }
    
    
    private fun setupRecyclerView() {
        userAdapter = UserAdapter(
            onEditClick = { user ->
                handleEditUser(user)
            },
            onDeleteClick = { user ->
                handleDeleteUser(user)
            },
            onLoadMoreClick = {
                loadMoreUsers()
            }
        )
        
        _binding?.recyclerView?.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = userAdapter
            // 设置固定大小以提高性能
            setHasFixedSize(true)
        }
    }
    
    private fun setupSearchFunction() {
        _binding?.let { binding ->
            // 设置搜索框点击事件，确保可以正常获取焦点
            binding.searchEditText.setOnClickListener {
                binding.searchEditText.isFocusable = true
                binding.searchEditText.isFocusableInTouchMode = true
                binding.searchEditText.requestFocus()
            }
            
            binding.searchButton.setOnClickListener {
                val query = binding.searchEditText.text.toString().trim()
                if (query.isNotEmpty()) {
                    userViewModel.searchUsers(query)
                } else {
                    userViewModel.refreshUsers()
                }
            }
            
            // 添加回车键搜索功能
            binding.searchEditText.setOnEditorActionListener { _, _, _ ->
                binding.searchButton.performClick()
                true
            }
        }
    }
    
    private fun setupObservers() {
        // 观察用户数据变化
        userViewModel.users.observe(viewLifecycleOwner) { users ->
            userAdapter.setUsers(users)
            updateEmptyState(users.isEmpty())
            updateStatistics(users.size)
            // 停止下拉刷新动画
            _binding?.swipeRefreshLayout?.isRefreshing = false
            // 重置防抖标志，允许下次触发加载
            isLoadingMore = false
        }
        
        // 观察总用户数
        userViewModel.totalCount.observe(viewLifecycleOwner) { totalCount ->
            updateLoadMoreVisibility(totalCount)
            updateTotalCount(totalCount)
        }
        
        // 观察加载状态
        userViewModel.loading.observe(viewLifecycleOwner) { isLoading ->
            _binding?.progressBar?.visibility = if (isLoading) View.VISIBLE else View.GONE
            // 如果正在加载，确保下拉刷新动画也显示
            if (isLoading) {
                _binding?.swipeRefreshLayout?.isRefreshing = true
            } else {
                _binding?.swipeRefreshLayout?.isRefreshing = false
            }
        }
        
        // 观察错误信息
        userViewModel.error.observe(viewLifecycleOwner) { errorMessage ->
            errorMessage?.let {
                Toast.makeText(context, it, Toast.LENGTH_LONG).show()
            }
            // 出错时也停止下拉刷新动画
            _binding?.swipeRefreshLayout?.isRefreshing = false
        }
    }
    
    private fun setupRefreshLayout() {
        _binding?.swipeRefreshLayout?.setOnRefreshListener {
            userViewModel.refreshUsers()
        }
        
        // 设置刷新提示文字
        _binding?.swipeRefreshLayout?.setColorSchemeResources(
            android.R.color.holo_blue_bright,
            android.R.color.holo_green_light,
            android.R.color.holo_orange_light,
            android.R.color.holo_red_light
        )
    }
    
    private fun setupAddUserButton() {
        _binding?.btnAddUser?.setOnClickListener {
            showAddUserDialog()
        }
    }
    
    private fun setupResetButton() {
        _binding?.btnReset?.setOnClickListener {
            // 清空搜索框
            _binding?.searchEditText?.setText("")
            // 重新加载所有用户
            userViewModel.refreshUsers()
        }
    }
    
    private fun setupToggleSearch() {
        _binding?.tvToggleSearch?.setOnClickListener {
            toggleSearchCard()
        }
    }
    
    private fun toggleSearchCard() {
        _binding?.let { binding ->
            val isExpanded = binding.searchCard.visibility == View.VISIBLE
            if (isExpanded) {
                // 收起：隐藏查询卡片
                binding.searchCard.visibility = View.GONE
                binding.tvToggleSearch.text = "展开 ▼"
            } else {
                // 展开：显示查询卡片
                binding.searchCard.visibility = View.VISIBLE
                binding.tvToggleSearch.text = "收起 ▲"
            }
        }
    }
    
    private fun setupLoadMoreListener() {
        // 监听RecyclerView的滚动，实现上拉加载更多
        _binding?.recyclerView?.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                
                val layoutManager = recyclerView.layoutManager as LinearLayoutManager
                val visibleItemCount = layoutManager.childCount
                val totalItemCount = layoutManager.itemCount
                val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()
                
                // 当滚动到倒数第3个item时，自动加载更多
                if (!isLoadingMore &&
                    userViewModel.loading.value != true && 
                    userViewModel.hasMoreData() &&
                    (visibleItemCount + firstVisibleItemPosition) >= totalItemCount - 3 &&
                    firstVisibleItemPosition >= 0) {
                    // 设置防抖标志
                    isLoadingMore = true
                    // 使用post延迟执行，避免在滚动回调中修改RecyclerView数据
                    recyclerView.post {
                        loadMoreUsers()
                    }
                }
            }
        })
    }
    
    private fun loadMoreUsers() {
        // 添加防重复调用检查
        if (userViewModel.hasMoreData() && 
            userViewModel.loading.value != true && 
            !userAdapter.isLoadingMore()) {
            userViewModel.loadMoreUsers()
            userAdapter.setLoadingMore(true)
        } else {
            // 重置防抖标志
            isLoadingMore = false
        }
    }
    
    private fun updateLoadMoreVisibility(totalCount: Int) {
        val currentUserCount = userViewModel.users.value?.size ?: 0
        val hasMore = currentUserCount < totalCount
        
        if (hasMore) {
            userAdapter.setShowLoadMore(true)
            userAdapter.setLoadingMore(false)
        } else {
            // 没有更多数据时，显示提示
            userAdapter.setNoMoreData(true)
        }
    }
    
    private fun clearSearchFocus() {
        // 清除搜索框焦点，避免自动弹出键盘
        _binding?.let { binding ->
            binding.searchEditText.clearFocus()
            // 隐藏软键盘
            val imm = requireActivity().getSystemService(android.content.Context.INPUT_METHOD_SERVICE) as android.view.inputmethod.InputMethodManager
            imm.hideSoftInputFromWindow(binding.searchEditText.windowToken, 0)
        }
    }
    
    private fun setupEmptyState() {
        _binding?.let { binding ->
            // 自定义空状态的图标和文字
            binding.root.findViewById<ImageView>(cn.harry.cabinet.R.id.emptyStateIcon)?.apply {
                setImageResource(cn.harry.cabinet.R.drawable.ic_user)
            }
            binding.root.findViewById<TextView>(cn.harry.cabinet.R.id.emptyStateTitle)?.text = "暂无用户数据"
            binding.root.findViewById<TextView>(cn.harry.cabinet.R.id.emptyStateMessage)?.text = "点击上方\"添加新用户\"按钮开始添加"
        }
    }
    
    private fun updateEmptyState(isEmpty: Boolean) {
        _binding?.let { binding ->
            binding.emptyView.root.visibility = if (isEmpty) View.VISIBLE else View.GONE
            binding.recyclerView.visibility = if (isEmpty) View.GONE else View.VISIBLE
        }
    }
    
    private fun updateStatistics(filteredCount: Int) {
        _binding?.let { binding ->
            binding.root.findViewById<TextView>(cn.harry.cabinet.R.id.tvFilteredCount)?.text = "筛选结果: $filteredCount"
        }
    }
    
    private fun updateTotalCount(totalCount: Int) {
        _binding?.let { binding ->
            binding.root.findViewById<TextView>(cn.harry.cabinet.R.id.tvTotalCount)?.text = "总数: $totalCount"
        }
    }
    
    
    private fun handleEditUser(user: User) {
        showEditUserDialog(user)
    }
    
    private fun handleDeleteUser(user: User) {
        showDeleteConfirmationDialog(user)
    }
    
    private fun showAddUserDialog() {
        // 创建添加用户对话框
        val dialog = UserFormDialogFragment(
            user = null, // null表示添加模式
            onUserSaved = { newUser ->
                userViewModel.addUser(newUser) {
                    Toast.makeText(context, "用户添加成功", Toast.LENGTH_SHORT).show()
                    
                    // 记录添加用户日志
                    requireContext().logConfigChange(
                        scope = viewLifecycleOwner.lifecycleScope,
                        subType = "USER_ADD",
                        description = "添加用户: ${newUser.name}",
                        oldValue = "",
                        newValue = "姓名: ${newUser.name}, 工号: ${newUser.employeeId}, 职位: ${newUser.position ?: "(空)"}"
                    )
                }
            }
        )
        dialog.show(childFragmentManager, "UserFormDialog")
    }
    
    private fun showEditUserDialog(user: User) {
        // 创建编辑用户对话框
        val dialog = UserFormDialogFragment(
            user = user, // 传入用户对象表示编辑模式
            onUserSaved = { updatedUser ->
                userViewModel.updateUser(updatedUser) {
                    Toast.makeText(context, "用户信息更新成功", Toast.LENGTH_SHORT).show()
                    
                    // 记录更新用户日志
                    val changes = mutableListOf<String>()
                    if (user.name != updatedUser.name) changes.add("姓名: ${user.name} → ${updatedUser.name}")
                    if (user.employeeId != updatedUser.employeeId) changes.add("工号: ${user.employeeId} → ${updatedUser.employeeId}")
                    if (user.position != updatedUser.position) changes.add("职位: ${user.position ?: "(空)"} → ${updatedUser.position ?: "(空)"}")
                    if (user.phoneNumber != updatedUser.phoneNumber) changes.add("电话: ${user.phoneNumber ?: "(空)"} → ${updatedUser.phoneNumber ?: "(空)"}")
                    if (user.status != updatedUser.status) changes.add("状态: ${user.status} → ${updatedUser.status}")
                    
                    if (changes.isNotEmpty()) {
                        requireContext().logConfigChange(
                            scope = viewLifecycleOwner.lifecycleScope,
                            subType = "USER_UPDATE",
                            description = "更新用户: ${user.name} - ${changes.joinToString(", ")}",
                            oldValue = "姓名: ${user.name}, 工号: ${user.employeeId}",
                            newValue = changes.joinToString("\n")
                        )
                    }
                }
            }
        )
        dialog.show(childFragmentManager, "UserFormDialog")
    }
    
    private fun showDeleteConfirmationDialog(user: User) {
        // 创建删除确认对话框
        val dialog = DeleteConfirmationDialogFragment(user.name) {
            userViewModel.deleteUser(user) {
                Toast.makeText(context, "用户删除成功", Toast.LENGTH_SHORT).show()
                
                // 记录删除用户日志
                requireContext().logConfigChange(
                    scope = viewLifecycleOwner.lifecycleScope,
                    subType = "USER_DELETE",
                    description = "删除用户: ${user.name}",
                    oldValue = "姓名: ${user.name}, 工号: ${user.employeeId}, 职位: ${user.position ?: "(空)"}",
                    newValue = "已删除"
                )
            }
        }
        dialog.show(childFragmentManager, "DeleteConfirmationDialog")
    }
    
    
    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}